﻿using System.Text;
using UnityEngine;
using ZFramework.Runtime;
using ZFramework.Runtime.DataCenter;
using ZFramework.Runtime.WebRequest;

namespace ZGame
{
    public class MGameServerMgr : DataCenter
    {
        private string _gatewayUrl = "http://172.16.10.57:3000";
        private string _gatewayPath = "/auth/";
        private string _serverListPath = "/auth/servers";
        
        private int _reqServerListRequestId;
        private int _gateLoginRequestId;

        private ServersInfo _curServersInfo;
        private LoginSuccessParams _gateLoginSuccessParams;
        public override void Init()
        {
            _reqServerListRequestId = -1;
            _gateLoginRequestId = -1;
            _curServersInfo = null;
            _gateLoginSuccessParams = null;
        }

        public override void Preload()
        {
        }

        public override void Load()
        {
        }

        public override void Unload()
        {
        }

        public override void Shutdown()
        {
        }

        //请求游戏服务器列表
        public void RequestServerList()
        {
            var url = Utility.Text.Format("{0}{1}", _gatewayUrl, _serverListPath);
            var param = new RequstServerListParams();
            param.platform = 1000;
            param.uid = "c6c820b859b19f8a84d454b550f4d755fc8fa9d";
            param.version = "3.0.1705388933";
            string json = JsonUtility.ToJson(param);
            byte[] body = Encoding.UTF8.GetBytes(json);
            _reqServerListRequestId = AOTGameEntry.webRequestManager.AddWebRequest(url, body, 0, "application/json;charset=utf-8");
        }

        //登录网关，获取游戏服务器信息
        public void LoginGateWay()
        {
            
        }
        
        private void OnRequstServerListCallback(WebRequestSuccessEventArgs e)
        {
            string data = Utility.Converter.GetString(e.GetWebResponseBytes());
            var serversInfo = JsonUtility.FromJson<ServersInfo>(data);
            _curServersInfo = serversInfo;
        }

        private void OnLogin(WebRequestSuccessEventArgs e)
        {
            string data = Utility.Converter.GetString(e.GetWebResponseBytes());
            Log.Error($"登录成功, data=={data}");
            var loginSuccessParams = JsonUtility.FromJson<LoginSuccessParams>(data);
            _gateLoginSuccessParams = loginSuccessParams;
        }
    }
}